﻿/// <summary>
/// Summary description for StringExtension
/// </summary>
using System;
using System.Text.RegularExpressions;
public static class StringExtension
{
    public static string PadLeft(this string str, int totalWidth, string paddingString)
    {
        int i = str.Length;
        for (; i < totalWidth; i++)
        {
            str = str.Insert(0, paddingString);
        }

        return str;
    }

    public static string CutWords(this string originalString, int numberChars)
    {
        string[] arrayString = originalString.Split(' ');
        if (arrayString.Length > numberChars)
        {
            return String.Join(" ", arrayString, 0, numberChars) + " ...";
        }
        else
            return originalString;
    }

    public static string ToFilename(this string value)
    {
        return value.RemoveMarks().RemoveSpecialCharacters('_');
    }

    static string RemoveSpecialCharacters(this string input, char c)
    {
        Regex r = new Regex("(?:[^a-z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
        return r.Replace(input, String.Empty).SpaceToC(c);
    }

    static string RemoveMarks(this string input)
    {
        Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
        string strFormD = input.Normalize(System.Text.NormalizationForm.FormD);
        return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
    }

    /// <summary>
    /// c is '-' Space to Stroke
    /// c is '_' Space to underline
    /// </summary>
    /// <param name="input"></param>
    /// <param name="c"></param>
    /// <returns></returns>
    static string SpaceToC(this string input, char c)
    {
        input = input.Replace(' ', c);
        string doubleC = String.Concat(c, c);
        while (input.Contains(doubleC))
        {
            input = input.Replace(doubleC, c.ToString());
        }
        return input;
    }
}